package cn.ittgh.service.Files.TencentFiles.impl;

import cn.hutool.core.date.DateUtil;
import cn.ittgh.mapper.Image.ImageMapper;
import cn.ittgh.mapper.User.UserMapper;
import cn.ittgh.pojo.Image.Image;
import cn.ittgh.pojo.User.User;
import cn.ittgh.service.Files.TencentFiles.TencentFilesService;
import cn.ittgh.utils.ThreadLocalUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class TencentFilesServiceImpl implements TencentFilesService {
	@Value("${files.tencent.secretId}")
	private String secretId;
	@Value("${files.tencent.secretKey}")
	private String secretKey;
	@Value("${files.tencent.bucketName}")
	private String bucketName;
	@Value("${files.tencent.region}")
	private String region;

	@Value("${files.tencent.path}")
	private String filePath;

	@Value("${files.tencent.env}")
	private String fileEnv;

	@Value("${files.tencent.maxSize}")
	private Integer maxSize;

	@Autowired
	private ImageMapper imageMapper;

	@Autowired
	private UserMapper userMapper;

	/**
	 * 上传文件到腾讯云cos
	 *
	 * @param file 上传的文件
	 * @return 文件在cos上的访问url
	 */
	@Override
	public Map<String, String> uploadFiles(MultipartFile file) {
		// 初始化cos客户端
		COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
		ClientConfig clientConfig = new ClientConfig(new Region(region));
		COSClient cosClient = new COSClient(cred, clientConfig);

		try {
			String oldName = file.getOriginalFilename();
			assert oldName != null;
			String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);

			// 生成唯一文件名，当前时间 + 随机UUID + 文件类型
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "-" + UUID.randomUUID() + "." + suffix;

			// 上传文件到cos
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(file.getSize());
			InputStream inputStream = file.getInputStream();
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath + fileEnv + "/" + fileName, inputStream, metadata);
			cosClient.putObject(putObjectRequest);
			inputStream.close();

			// 返回文件在cos上的访问url
			String url = "https://" + bucketName + ".cos." + region + ".myqcloud.com/" + filePath + fileEnv + "/" + fileName;

			Image image = new Image(UUID.randomUUID().toString(), ThreadLocalUtil.getUserId(), file.getOriginalFilename(), fileName, url);

			// add image
			imageMapper.add(image);

			Map<String, String> fileMap = new HashMap<>();
			fileMap.put("fileId", image.getId());
			fileMap.put("fileName", fileName);
			fileMap.put("fileOriName", image.getTitle());
			fileMap.put("filePath", image.getPath());

			return fileMap;
		} catch (IOException e) {
			throw new RuntimeException("上传失败");
		} finally {
			// 关闭cos客户端
			cosClient.shutdown();
		}
	}

	@Override
	public String deleteImage(String id) {
		// 初始化用户身份信息(secretId, secretKey)
		COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

		// 设置bucket的区域
		ClientConfig clientConfig = new ClientConfig(new Region(region));

		// 生成cos客户端
		COSClient cosClient = new COSClient(cred, clientConfig);

		Image image = imageMapper.getImageByIdOrPath(id);

		try {
			// delete tencent obj image
			cosClient.deleteObject(bucketName, filePath + fileEnv + "/" + image.getFileName());
			// delete database tb_images
			imageMapper.deleteImageById(image.getId());

			return "删除成功";
		} catch (CosClientException e) {
			return e.getErrorCode() + ":" + e.getMessage();
		} finally {
			cosClient.shutdown();
		}
	}
}
